import { Getter, Mutation, Action } from 'vuex'
import { UserInfo } from '@/types/types'
import { login as l, checkToken as c } from '&/user'
import { SUCCESS_CODE } from '@/config/requestCode'
import loading from '@/utils/globalLoading'
import { TODOAUTH } from '@/config/constant'
import { SETUSERINFO, LOGIN, CHECKTDAUTH, GETUSERINFO } from './types'
import Cookie from '@/utils/cookie'
import { openMessage } from '@/utils/elComponents'

type State = {
  userInfo: UserInfo
}

const state: State = {
  userInfo: {
    nikeName: '',
    realName: '',
    phone: '',
    country: '',
    national: '',
    address: '',
    hobby: '',
    job: '',
    signature: '',
    profile: '',
    defaultGroup: '',
    birthday: '',
    gender: ''
  }
}

const getters: { [propName: string]: Getter<State, State> } = {
  [GETUSERINFO](state) {
    return state.userInfo
  }
}

const mutations: { [propName: string]: Mutation<State> } = {
  [SETUSERINFO](state: State, data: UserInfo) {
    state.userInfo = data
  }
}

const actions: { [propName: string]: Action<State, State> } = {
  [LOGIN](context, data: FormData) {
    return new Promise((resolve, reject) => {
      loading.show()
      l(data).then(resp => {
        if (resp && resp.code == SUCCESS_CODE) {
          context.commit(SETUSERINFO, resp.data.userInfo)
          Cookie.set(TODOAUTH, resp.data[TODOAUTH])
          resolve(true)
          return
        }
        loading.hide()
        openMessage('error', resp.msg)
        reject(new Error(resp.msg))
      }, err => {
        loading.hide()
        openMessage('error', err.message)
        reject(err)
      })
    })
  },
  [CHECKTDAUTH](context) {
    return new Promise((resolve, reject) => {
      const todoAuth = Cookie.get(TODOAUTH)
      if (!todoAuth) {
        reject(new Error('Please login!'))
        return
      }

      c().then(resp => {
        if (resp && resp.code == SUCCESS_CODE && !resp.data.expired) {
          context.commit(SETUSERINFO, resp.data.userInfo)
          resolve(true)
        } else {
          Cookie.remove(TODOAUTH)
          reject(new Error('Auth expired!'))
        }
      }, err => {
        reject(err)
      })
    })
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
